package com.xkstream.client.base;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.UiThread;
import android.support.v4.app.FragmentActivity;
import android.util.AndroidRuntimeException;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.androidadvance.topsnackbar.TSnackbar;
import com.umeng.analytics.MobclickAgent;
import com.xkstream.client.R;
import com.xkstream.client.appmanager.AppManager;
import com.xkstream.client.common.CommonDialog;
import com.xkstream.client.rx.Rxbus;
import com.xkstream.client.ui.LoginActivity_V2;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.utils.LogUtil;
import com.xkstream.client.utils.ToastUtils;
import com.xkstream.client.view.LoadingDialog;

import butterknife.BindString;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by xiaoyi on 2016/8/15.
 * Activity基类，抽象类
 * 定义了Activity通用部分
 *
 * @
 * @see {oncreate()}
 * 采用注解的方式设置布局文件ID@see{LayoutId.class}
 * 在Base中使用Butterknife注入
 * 将oncreate()方法设置为final(包含了初始化模板，不应被重写)
 * <p/>
 * 其他说明：
 * @see {Title.class}
 * activity标题使用了注解的方式
 * 另外针对某些页面标题会动态改变的
 * 提供了一个方法@see{setTitle(String str)}
 * @see {showBack()}
 * <p/>
 * 提供两个showBack()方法
 * 可以替换左上角back图标
 * 通常情况下不需要调用，也不需要设置点击事件
 * 对于某些界面不要显示back按钮的，需要在初始化的时候调用@see{hideBack()}
 * <p/>
 * 子类应该实现@see{initViews(Bundle saveInstance)}
 * 需要注意的是：此BaseAppCompatActivity的初始化采用了模板方法模式
 * 子类无需关注初始化过程，只需要实现相应的方法即可
 * 请各位在开发的时候遵照上述协议
 * 如果有更好的建议也可以商讨之后修改
 * 另外，Base类里面的代码应该是通用的，所有子类都会或者潜在意义的会使用到
 * 所以，请各位在修改Base类的时候注意一下，对于不属于通用代码部分，尽可能
 * 不要写在Base中
 */
public abstract class BaseActivity<T extends BasePresenter> extends FragmentActivity {
    public T presenter;

    protected final String TAG = getClass().getSimpleName();
    LoadingDialog progressDialog = null;

    private TSnackbar snackbar;

    protected boolean pause;

    @BindString(R.string.token_err)
    String strTokenErr;
    private Disposable disposable;

    @Override
    public final void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //      ButterKnife.bind(this);
        //       setTitle("");
        initViews(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        LogUtil.i(TAG + "---------------------------------", "onCreate");
        registerTokenRxbus();
    }


    protected abstract void initViews(Bundle savedInstanceState);


    /**
     * findview
     *
     * @param resId viewId
     * @param <T>
     * @return view
     */
    protected <T extends View> T findView(int resId) {
        return (T) findViewById(resId);
    }

    /**
     * findview
     *
     * @param resId viewId
     * @param group ViewGroup
     * @param <T>
     * @return view
     */
    protected <T extends View> T findView(View group, int resId) {
        return (T) group.findViewById(resId);
    }

    @UiThread
    protected void showToast(int resId) {
        ToastUtils.show(resId);
    }

    @UiThread
    protected void showToast(String msg) {
        ToastUtils.show(msg);
    }

    @UiThread
    protected void showToast(String msg, int duration) {
        ToastUtils.show(msg, duration);
    }

    @UiThread
    protected void showToast(int resId, int duration) {
        ToastUtils.show(resId, duration);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //注：回调 2
        //      Bugtags.onPause(this);
        MobclickAgent.onPause(this);
        LogUtil.i(TAG + "---------------------------------", "onpause");
        pause = true;
    }


    @Override
    protected void onDestroy() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        AppManager.getAppManager().finishActivity(this);
        releasePresenter();
        super.onDestroy();
        LogUtil.i(TAG + "---------------------------------", "onDestroy");
        disposable.dispose();
    }


    protected void jumpToActivity(@NonNull Class clazz) {
        jumpToActivity(clazz, null);
    }

    protected void jumpToActivity(@NonNull Class clazz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    protected void jumpToActivity(@NonNull Intent intent) {
        startActivity(intent);
    }

    protected void jumpToActivityForResult(@Nullable Class clazz, int requestCode) {
        jumpToActivityForResult(clazz, requestCode, null);
    }

    protected void jumpToActivityForResult(@Nullable Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode);
    }

    protected void jumpToActivityForResult(@Nullable Class clazz, int requestCode, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注：回调 1
        //      Bugtags.onResume(this);

        MobclickAgent.onResume(this);
        pause = false;
        LogUtil.i(TAG + "---------------------------------", "onResume");
    }

    /**
     * 要显示的文本
     *
     * @param text
     */
    public void showLoading(String text, boolean isCanceled) {
        LogUtil.e(TAG, "showLoading tag : " + TAG + " thread : " + Thread.currentThread().getName());
        if (progressDialog == null) {
//            progressDialog = LoadingDialog.createDialog(WangYuApplication.appContext, text);
            progressDialog = LoadingDialog.createDialog(this, text);
            progressDialog.show();
        } else if (!progressDialog.isShowing()) {
            try {
                progressDialog.show();
            } catch (AndroidRuntimeException e) {
                e.printStackTrace();
            }
        }else {
            LogUtil.e(TAG,"showLoading  is showing");
        }
        if (isCanceled) {
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
        } else {
            progressDialog.setCancelable(true);
            progressDialog.setCanceledOnTouchOutside(true);
        }
    }

    /**
     * 显示Loading框
     * <p>
     * 提示文本默认为“正在加载”
     */
    public void showLoading() {
        try {
            this.showLoading(null, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将显示的Loading框关闭
     */
    public void hideLoading() {
        LogUtil.e(TAG, "hideLoading tag : " + TAG + " thread : " + Thread.currentThread().getName());
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        //注：回调 3
        //     Bugtags.onDispatchTouchEvent(this, event);
        return super.dispatchTouchEvent(event);
    }

    private void releasePresenter() {
        if (presenter != null) {
            presenter.unSubscribe();
        }
    }

    @UiThread
    public void showTopTips(String tips) {
        snackbar = TSnackbar.make(getRootView(), tips, TSnackbar.LENGTH_SHORT);
        View snackbarView = snackbar.getView();
        snackbarView.setBackgroundColor(getResources().getColor(R.color.toptips));
        snackbarView.setMinimumHeight(DeviceUtils.dp2px(this, 73));
        TextView tv = (TextView) snackbarView.findViewById(R.id.snackbar_text);
        tv.setTextColor(this.getResources().getColor(R.color.white));
        tv.setGravity(Gravity.CENTER);
        snackbar.show();
    }

    @UiThread
    public void showTopTips(@StringRes int resID) {
        showTopTips(getResources().getString(resID));
    }

    private View getRootView() {
        return findViewById(android.R.id.content);
    }

    public void setTitle(int resId) {
        setTitle(getResources().getString(resId));
    }

    public void setTitle(String title) {
        TextView tvTitle = (TextView) findViewById(R.id.headerTitle);
        if (tvTitle != null)
            tvTitle.setText(title);
    }

    private void showTokenErrorDialog(){
        if (pause)return;
        CommonDialog dialog = new CommonDialog(this);
        dialog.setTitle(strTokenErr);
        dialog.setListener(() -> {
            errorTokenAction();
        });
        dialog.show();
    }

    protected void errorTokenAction(){
        jumpToActivity(LoginActivity_V2.class);
    }

    private void registerTokenRxbus(){
      disposable =   Rxbus.getDefault().register(String.class)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((value)->{
                    if (value.equals("token_error")){
                        showTokenErrorDialog();
                    }
                });
    }
}
